<?php

// +----------------------------------------------------------------------
// |目录权限服务层
// +----------------------------------------------------------------------

namespace app\admin\system;

use app\admin\Model\MenuModel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 目录权限
 */
class MenuService
{

    /**
     * 获取的菜单的数据
     * @param array $param 前台传过来的参数  
     * @return array
     */
    public static function  getlist($param){
        
        $MenuModel = new MenuModel(); 
        $pk = $MenuModel->getPk();      
        $params= $param['params'];
        $field = $pk . ',title,pid,icon,url,sort,ismenu,status';   
        $where = [];    
        if($params['title']){
            $where[] = ['title', 'like', '%'. $params['title']. '%'];
        }
        if($params['ismenu']==2){
            $where[] = ['ismenu', '=', 0];
        }else  if($params['ismenu']==1){
            $where[] = ['ismenu', '=', 1];
        } 
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        } 
       

        $menu_list = $MenuModel->field($field)->where($where)->order('sort asc,id asc,status asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray(); 
        
        if($menu_list['data']){
            foreach ($menu_list['data'] as $key => $value) {
                  // 找到 '/index/' 的位置
             
                if (strpos($value['url'], '/index/') !== false) {
                    // 提取 '/index/' 部分
                    $indexPosition = strpos($value['url'], '/index/');
                    $menu_list['data'] [$key]['prefix'] = substr($value['url'], 0, $indexPosition + strlen('/index/'));
                    // 提取剩余部分
                    $menu_list['data'] [$key]['urls']= substr($value['url'], $indexPosition + strlen('/index/'));
       
                } elseif (strpos($value['url'], '/admin/')!== false) {
                    // 提取 '/index/' 部分
                    $indexPosition = strpos($value['url'], '/admin/');
                    $menu_list['data'] [$key]['prefix'] = substr($value['url'], 0, $indexPosition + strlen('/admin/'));
                    // 提取剩余部分
                    $menu_list['data'] [$key]['urls']= substr($value['url'], $indexPosition + strlen('/admin/'));
                }           

            }
        } 
       
         if($params['title'] ){
            $parent=getAllparentIds(new MenuModel(),array_column($menu_list['data'],'pid'));         
           // 合并两个数组
            $mergedArray = array_merge($menu_list['data'],  $parent);          
            $uniqueArray = [];
            // 用于记录已经出现过的键
            $seenKeys = [];            
            foreach ($mergedArray as $subArray) {
                // 假设以 'id' 作为唯一标识
                $key = $subArray['id'];
                if (!isset($seenKeys[$key])) {
                    $seenKeys[$key] = true; // 标记该键已出现
                    $uniqueArray[] = $subArray; // 添加到去重后的数组
                }
            }        
            $data['total']=(int)count($uniqueArray);
            $datas=buildTree($uniqueArray);      
            $data['list']=$datas;
          
            
         }else{
            $data['total']=$menu_list['total'];
            if($params['ismenu']==2 || $params['ismenu'] || $params['status']){
                //等于2  说明前台选择不是菜单，不是菜单则不显示树状
                $data['list']=$menu_list['data'];
            }else{          
                $data['list']=buildTree($menu_list['data']);
            }
         }
       
      
        return $data;
     }

     /**
     * 修改菜单是否为菜单
     * @param array $param 前台传过来的参数  
     * @return array
     */
     public static function  update_ismenus($param){ 
            $MenuModel = new MenuModel();
            $params= $param['params'];
            $idarr=getAllChildrenIds(new MenuModel(),$params['id']);
            $idarr[]=$params['id'];
            $result =  $MenuModel->where('id','in',$idarr)->update(['ismenu' => $params['ismenu']]);
            if($result){
                return true;
            }else{
                error('修改失败');
            }
     
    }

      /**
     * 获取所有菜单列表
 
     * @return array
     */       
    public static function list(){
        $MenuModel = new MenuModel(); 
        $pk = $MenuModel->getPk();         
        $field = $pk . ',title ,laval,pid';   
        $where[] = ['status', '=', 1];    
        $menu_list = $MenuModel->field($field)->where($where)->order('sort asc,id asc')->select()->toArray();       
        $data=buildTree($menu_list);
         
        return  skusGroupMerge($data);
    }

     /**
     * 菜单禁用
     * @param array $param 前台传过来的参数  
     * @return array
     */   
    public static function delete($param){
        $MenuModel = new MenuModel();
        $params= $param['params'];
        $idarr=getAllChildrenIds(new MenuModel(),$params['id']);    
        $idarr[]=$params['id'];
        $result =  $MenuModel->where('id','in',$idarr)->update(['status' => 0]);
        if($result){
            return true;
        }else{
            error('修改失败');   
         }
      
    }



     /**
     * 修改菜单是否为菜单
     * @param array $param 前台传过来的参数  
     * @return array
     */   
    public static function create($param){
        $MenuModel = new MenuModel();
        $params= $param['params'];     


       //查询等级，最多级别为3级  
       if($params['pid']>0){
            $pid =  $MenuModel->where('id',  $params['pid'])->field('laval')->find();
       }else{
            $pid['laval']=0;
       }
          
        $laval =  $MenuModel->where('id',$params['id'])->field('laval')->find();//查询当前等级
        if($pid['laval']==3){
            error('最多只能创建3级菜单');            
        }     
    
        //查看等级

        if(empty($laval) && $pid['laval'] >=0 ){              
            $laval=$pid['laval']+1;
        }elseif($laval['laval']<$pid['laval']){                           
            $laval=$laval['laval']+($pid['laval']-$laval['laval']);
        }elseif($laval['laval']==0){          
            $laval=$laval['laval']+1;
        }else{
            $laval=$laval['laval']+($laval['laval']-$pid['laval']);
        }

      
        if(isset($params['urls']) && $params['urls']){
            $url = $params['prefix'].$params['urls'];
        }else{
            $url = $params['prefix'];
        }
     
        $data=[
            'icon'=> $params['icon'],
            'title' => $params['title'],
            'status' => $params['status'],
            'pid' =>  $params['pid'],        
            'url' =>  $url,
            'sort' => $params['sort'],
            'ismenu' => $params['ismenu'],
            'laval' => $laval,
        ];
       
        if($params['id']){
            //有值则说明是修改        
                $res =  $MenuModel->where('id','in',$params['id'])->field('status,ismenu')->find()->toArray();
                if($res['status']!=$params['status'] || $res['ismenu']!=$params['ismenu']){                   
                    //如果数据状态和是否菜单有变化，则更新所有子级
                    //查询出所有子级 
                    $idarr=getAllChildrenIds(new MenuModel(),$params['id']);    
                    //有值说明有zid，则说明有子级，则更新所有子级
                    if($idarr){
                        $idarr[]=$params['id'];
                        $MenuModel->where('id',$params['id'])->update($data);
                        $result =  $MenuModel->where('id','in',$idarr)->update(['status' => $params['status'],'ismenu' => $params['ismenu']]);       
                    }else{
                        $result =  $MenuModel->where('id',$params['id'])->update($data);
                    }                 
                           
                }else{         
                    $result =  $MenuModel::update($data, ['id' => $params['id']]);
                    
                }
            
        }else{
            //执行添加数据
            $data['createtime']=datetime();
            $data['createymd']=(int)date('Ymd',time());
            $result =  $MenuModel->save($data);
        }
      
        if($result){
            return true;
        }else{
            error('修改失败');
        }
    
    }      
    
     



 
}